﻿#include <iostream>
#include <cmath>

using namespace std;

#define VOLT_BIT1  -15.0    // 表示1的电压
#define VOLT_BIT0  15.0     // 表示0的电压

int rs232c_encode(double* volts, int volts_size, const char* msg, int size)
{
    if (!volts || volts_size < (size * 9 + 1)) 
        return -1;          // 电压数组空间不足
    for (int i = 0; i < size; i++,msg++)
    {
        int bit = 1;
        *volts = VOLT_BIT0; // 开始电压
        volts++;
        for (int j = 0; j < 7; j++, volts++, bit= bit<< 1)
        {
            if (*msg & bit)
                *volts = VOLT_BIT1;
            else
                *volts = VOLT_BIT0;
        }
        *volts = VOLT_BIT1; // 结束电压
        volts++;
    }
    return 1;
}

int rs232c_decode(char* msg, int size, const double* volts, int volts_size)
{
    if (!msg || size < ((volts_size - 1) / 9))
        return -1;         // 字符数组空间不足
    while (volts_size)
    {
        char ch = 0;
        int bit = 1;
        while (*volts != VOLT_BIT0)    volts++;// 读到开始位再解码
        volts++;
        for (int j = 0; j < 7; j++, bit= bit<<1, volts++)
        { 
            if(*volts==VOLT_BIT1)
                ch += bit;
        }
        *msg = ch;
        msg++;
        volts_size -= 9;
    }
    return 1;
}

void check_output(const double* volts)
{
    int i = 0;
    while (volts[i] != 0)
    {
        if (volts[i] > 0)  cout << "-";
        else    cout << "_";
        i++;
    }
}


int main()
{
    // test_1
    char in_msg[10] = {"abcdefg"};
    double out_volts[100] = { 0 };
    if (rs232c_encode(out_volts, 100, in_msg, 7) == -1)
    {
        cout << "encode_error" << endl;
        return 1;
    }
    check_output(out_volts);
    cout << endl;

    // test_2
    char out_msg[10] = { 0 };
    if (rs232c_decode(out_msg, 10, out_volts, 63 ) == -1)
    {
        cout << "decode_error" << endl;
        return 1;
    }    
    cout << out_msg;

    return 0;
}
